package com.wu.advapplication.servise;

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import com.wu.advapplication.MyBinderInterface;
import com.wu.advapplication.utils.BaseUtil;

import androidx.annotation.Nullable;

/**
 * 双进程守护
 */
public class LocalService extends Service {
    private static final String TAG = "ProcessService";
    private ServiceConnection serviceConnection;
    private MyBinder myBinder;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        myBinder = new MyBinder();
        serviceConnection = new MyServiceConnection();

        //让服务变成前台服务
        startForeground(10, new Notification());
        //如果api>18以上，使用相同id再启动一个前台服务，然后结束这个服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            startService(new Intent(this, InnerService.class));
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bindService(new Intent(this, RemoteService.class), serviceConnection, BIND_AUTO_CREATE);

        if (!BaseUtil.isServiceRunning(this,CustomTestService.class.getName())){
            startService(new Intent(this, CustomTestService.class));
        }

        return super.onStartCommand(intent, flags, startId);
    }

    class MyBinder extends MyBinderInterface.Stub{

    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e(TAG,"RemoteService 进程可能被干掉了，拉活");
            startService(new Intent(LocalService.this, RemoteService.class));
            bindService(new Intent(LocalService.this, RemoteService.class), serviceConnection, BIND_AUTO_CREATE);

        }
    }

    public static class InnerService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
            startForeground(10, new Notification());
            stopSelf();
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }

}
